package com.chensf.studydemo.common

import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.chensf.studydemo.R
import com.chensf.studydemo.extensions.tempCacheDir
import com.tencent.smtt.sdk.TbsReaderView
import kotlinx.android.synthetic.main.fragment_file_preview.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.concurrent.TimeUnit

class FilePreviewDemo :Fragment(){
    private lateinit var tbsReaderView:TbsReaderView

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return layoutInflater.inflate(R.layout.fragment_file_preview, container, false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        tbsReaderView = TbsReaderView(
            requireContext()
        ) { code, p1, p2 ->
            Log.e("foo", "reader callback code=$code, p1=$p1, p2=$p2")
        }
        rootView.addView(
            tbsReaderView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        lifecycleScope.launch(Dispatchers.Main){
            val file = withContext(Dispatchers.IO){
                Glide.with(this@FilePreviewDemo)
                    .asFile()
                    .load("https://imap-dev-pv.saicmotortest.com/test2020/test01.docx")
                    .submit()
                    .get(10, TimeUnit.SECONDS)
            }
            val filename = "test01.docx"
            val tempFile = File(requireContext().tempCacheDir, filename)
            file.copyTo(tempFile,true)

            val bundle = Bundle()
            bundle.putString("filePath", tempFile.absolutePath)
            bundle.putString("tempPath", requireContext().tempCacheDir.absolutePath)
            val result = tbsReaderView.preOpen(parseFormat(filename), false)
            tbsReaderView.openFile(bundle)
        }
    }
    private fun parseName(url: String): String? {
        var fileName: String? = null
        try {
            fileName = url.substring(url.lastIndexOf("/") + 1)
        } finally {
            if (TextUtils.isEmpty(fileName)) {
                fileName = System.currentTimeMillis().toString()
            }
        }
        return fileName
    }

    private fun parseFormat(fileName: String): String {
        return fileName.substring(fileName.lastIndexOf(".") + 1)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        tbsReaderView.onStop()

    }
}